#pragma once
#include<iostream>
#include"socket.hpp"
#include"protocol.hpp"

//封装fd,基类
class Connection{
    public:
        Connection(){}
        Connection(int fd):_fd(fd){}
        virtual ~Connection(){}
        virtual bool Send(){
            return true;
        }
        virtual int Recv(std::string& _inbuffer){
            while(true){
                char s[1024];
                int n=recv(_fd,s,1023,MSG_DONTWAIT);
                if(n<0){
                    if(errno==EAGAIN){
                        //LOG(ly::LogLevel::INFO)<<"没有数据"<<"\n";
                        break;
                    }
                    else if(errno==ECONNRESET){
                        //为什么这里会显示接收失败？不应该是对端关闭吗？？？？？？
                        LOG(ly::LogLevel::ERROR)<<"客户端被关闭了"<<"\n";
                        return n;
                    }
                    LOG(ly::LogLevel::ERROR)<<"接收失败"<<"\n";
                    return n;
                }
                else if(n==0){
                    LOG(ly::LogLevel::ERROR)<<"对端关闭"<<"\n";
                    //删除连接
                    return n;
                }
                else{
                    s[n-1]='\0';//Unix/Linux 系统：用 LF（\n）表示一行结束；
                    //std::cout<<n<<" "<<s<<std::endl;
                    _inbuffer.append(s,n);
                }
            }
            return 1;
        }
        //virtual bool Accept()=0;
        void SetFd(int fd){
            _fd=fd;
        }
        int GetFd(){
            return _fd;
        }
    private:
        int _fd;
};